<template>
  <view class="normal-login-container">
    <view class="toggle_tabs">
      <u-tabs
        :list="tabsList"
        :current="current"
        lineColor="#0f877c"
        @click="clickTab"
      ></u-tabs>
      <swiper
        class="swiper"
        :circular="false"
        :duration="200"
        :current="current"
        @change="changePlay"
        style="height: 100%"
      >
        <swiper-item>
          <view class="login_tab">
            <view class="login-form-content">
              <uni-forms
                ref="customForm"
                :modelValue="loginForm"
                label-position="top"
              >
                <uni-forms-item label="手机号" required name="username">
                  <uni-easyinput
                    v-model="loginForm.username"
                    placeholder="请输入手机号"
                  />
                </uni-forms-item>
                <uni-forms-item label="密码" required name="password">
                  <uni-easyinput
                    v-model="loginForm.password"
                    type="password"
                    placeholder="请输入密码"
                    class="password"
                  />
                </uni-forms-item>
                <uni-forms-item
                  label="验证码"
                  required
                  name="code"
                  style="position: relative"
                >
                  <uni-easyinput
                    v-model="loginForm.code"
                    placeholder="请输入验证码"
                    maxlength="4"
                    :clearable="false"
                  />
                  <view class="login-code">
                    <image
                      :src="codeUrl"
                      @click="getCode"
                      class="login-code-img"
                    ></image>
                  </view>
                </uni-forms-item>
              </uni-forms>
              <!-- 记住密码 -->
              <radio-group class="radio_group">
                <label>
                  <radio
                    style="transform:scale(0.7)"
                    @click="radioClick(1)"
                    :checked="radioSelect == 1 ? true : false"
                    :value="1"
                  />
                  <text>记住密码</text>
                </label>
              </radio-group>
              <button
                type="primary"
                class="sub_btn"
                @click="submitLogin('customForm')"
              >
                登录
              </button>
            </view>

            <view class="xieyi">
              <!-- <uni-data-checkbox
                multiple
                v-model="loginForm.isRead"
                :localdata="sexs"
              ></uni-data-checkbox> -->
              <view>
                登录即代表同意
                <text @click="handleUserAgrement" class="text_color"
                >用户协议</text
                >
                <text @click="handlePrivacy" class="text_color"
                >、隐私政策</text
                >
                相关条款内容
              </view>
            </view>
          </view>
        </swiper-item>
        <swiper-item>
          <view class="login_tab">
            <uni-forms
              ref="registerFormRef"
              :modelValue="registerForm"
              label-position="top"
            >
              <uni-forms-item label="手机号" required name="phonenumber">
                <uni-easyinput
                  v-model="registerForm.phonenumber"
                  placeholder="请输入手机号"
                  :clearable="false"
                />
              </uni-forms-item>
              <uni-forms-item
                label="昵称"
                required
                name="nickName"
              >
                <uni-easyinput
                  v-model="registerForm.nickName"
                  placeholder="请输入昵称"
                  :clearable="false"
                />
              </uni-forms-item>
              <uni-forms-item
                label="密码"
                required
                name="password"
              >
                <uni-easyinput
                  v-model="registerForm.password"
                  placeholder="请输入密码"
                  :clearable="false"
                  @input="inputPassWord"
                />
              </uni-forms-item>
              <uni-forms-item label="确认密码" required name="confirmPassword">
                <uni-easyinput
                  v-model="registerForm.confirmPassword"
                  placeholder="请输入密码"
                  :clearable="false"
                />
              </uni-forms-item>
            </uni-forms>
            <button
              type="primary"
              class="sub_btn"
              @click="registerLogin('registerFormRef')"
            >
              注册
            </button>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <image class="login_bg" :src="globalConfig.imgUrl + 'login/login_bg.png'" />
  </view>
</template>

<script>
import { getCodeImg, register } from "@/api/login";
import { getUserProfile } from "@/api/system/user";

export default {
  data() {
    return {
      radioSelect: 0,
      // 单选数据源
      sexs: [
        {
          text: "",
          value: 1,
        },
      ],
      current: 0,
      tabsList: [
        {
          name: "登录",
        },
        {
          name: "注册",
        },
      ],
      codeUrl: "",
      captchaEnabled: true,
      globalConfig: getApp().globalData.config,
      loginForm: {
        username: "",
        password: "",
        uuid: "",
        // isRead: 0,
        code: "",
        platform: "Visitor",
      },
      registerForm: {
        nickName: "",
        phonenumber: "",
        password: "",
        platform: "Visitor",
      },

      // 自定义表单校验规则
      customRules: {
        username: {
          rules: [
            {
              required: true,
              errorMessage: "手机号不能为空",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg =
                  /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/;
                if (!iphoneReg.test(value)) {
                  callback("手机号码格式不正确，请重新填写");
                }
              },
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: "密码不能为空",
            },
          ],
        },
        code: {
          rules: [
            {
              required: true,
              errorMessage: "请填写验证码",
            },
          ],
        },
      },
      // 注册校验
      registerRules: {
        // 手机号
        phonenumber: {
          rules: [
            {
              required: true,
              errorMessage: "请填写手机号码",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg =
                  /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/;
                if (!iphoneReg.test(value)) {
                  callback("手机号码格式不正确，请重新填写");
                }
              },
            },
          ],
        },
        // 昵称
        nickName: {
          rules: [
            {
              required: true,
              errorMessage: "昵称不能为空",
            },
          ],
        },
        // 密码
        password: {
          rules: [
            {
              required: true,
              errorMessage: "密码不能为空",
            },
          ],
        },
        confirmPassword: {
          rules: [
            {
              required: true,
              errorMessage: "确认密码不能为空",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let pwd = uni.getStorageSync("pwd_key");
                if (value != pwd) {
                  callback("两次密码输入不同，请重新输入");
                }
              },
            },
          ],
        },
      },
    };
  },
  onReady() {
    this.isSaveInfo();
    this.$refs.customForm.setRules(this.customRules);
    this.$refs.registerFormRef.setRules(this.registerRules);
  },
  created() {
    this.getCode();
  },
  methods: {
    // 记住密码
    radioClick(e) {
      if (e == this.radioSelect) {
        this.radioSelect = 0;
      } else {
        this.radioSelect = e;
      }
    },
    // 记住密码函数
    saveLoginInfo() {
      let data = {
        username: this.loginForm.username,
        password: this.loginForm.password,
        uuid: "",
        code: "",
        platform: "Visitor",
      };
      if (this.radioSelect) {
        uni.setStorageSync("loginForm", JSON.stringify(data));
      } else {
        uni.removeStorageSync("loginForm");
      }
    },

    // 判断用户是否记住密码
    isSaveInfo() {
      let isSave = uni.getStorageSync("loginForm") ? true : false;
      console.log(isSave, 'isSaveisSave');
      if (isSave) {
        this.loginForm = JSON.parse(uni.getStorageSync("loginForm"));
        console.log(this.loginForm, 'this.loginForm');
        this.radioSelect = 1;
      }
    },

    // 注册时，保存密码
    inputPassWord() {
      uni.setStorageSync("pwd_key", this.registerForm.password);
    },
    // 注册按钮
    registerLogin(ref) {
      console.log(this.registerForm);
      this.$refs[ref]
        .validate()
        .then((res) => {
          console.log(this.registerForm);
          const data = {
            phonenumber: this.registerForm.phonenumber,
            nickName: this.registerForm.nickName,
            password: this.registerForm.password,
            platform: this.registerForm.platform,
          };
          register(data)
            .then((res) => {
              if (res.code === 200) {
                this.current = 0;
                this.registerForm = {
                  nickName: "",
                  phonenumber: "",
                  password: "",
                  confirmPassword: "",
                  platform: "Visitor",
                };
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    submitLogin(ref) {
      // if (!this.loginForm.isRead.length) {
      //   uni.showToast({
      //     title: `请先同意用户协议`,
      //     icon: "exception",
      //   });
      //   return;
      // }
      this.$refs[ref]
        .validate()
        .then((res) => {
          this.pwdLogin();
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    // 滑动下面面板
    changePlay(e) {
      this.current = e.detail.current;
    },
    // 点击tab
    clickTab(item) {
      this.current = item.index;
    },

    // 用户注册
    handleUserRegister() {
      this.$tab.redirectTo(`/pages/register`);
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0];
      this.$tab.navigateTo(
        `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 用户协议
    handleUserAgrement() {
      let site = this.globalConfig.appInfo.agreements[1];
      this.$tab.navigateTo(
        `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 获取图形验证码
    getCode() {
      getCodeImg().then((res) => {
        console.log(res);
        this.loginForm.uuid = res.uuid;
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
        }
      });
    },

    // 密码登录
    async pwdLogin() {
      this.$store
        .dispatch("Login", this.loginForm)
        .then(() => {
          // 记住密码
          this.saveLoginInfo();
          this.$modal.closeLoading();
          this.loginSuccess();
        })
        .catch(() => {
          if (this.captchaEnabled) {
            this.getCode();
          }
        });
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
      // 设置用户信息
      this.$store.dispatch("GetInfo").then((res) => {
        const userInfo = uni.getStorageSync("userInfo");
        if (userInfo) {
        } else {
          getUserProfile().then((res) => {
            if (res.code === 200) {
              uni.setStorageSync("userInfo", JSON.stringify(res.data));
            }
          });
          // uni.getUserProfile({
          //   desc: "获取你的昵称、头像、地区及性别",
          //   success: (res) => {
          //     uni.setStorageSync("userInfo", JSON.stringify(res.userInfo));
          //   },
          //   fail(err) {
          //     console.log(err);
          //   },
          // });
        }
        this.$tab.switchTab("/pages/home/index");
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

// 重置样式
.u-tabs__wrapper__nav__item {
  width: 50%;
}

.uni-forms-item__label {
  font-size: 32rpx !important;
  font-weight: 500 !important;
  color: #333333 !important;
  padding: 0 !important;
  width: 200rpx !important;
}
.is-input-border {
  width: 654rpx !important;
  height: 88rpx !important;
  background: #f5f6f8 !important;
  border-radius: 224rpx 224rpx 224rpx 224rpx !important;
}

.uni-easyinput__content-input {
  font-size: 28rpx !important;
  font-weight: 400 !important;
  color: #999999 !important;
}

::v-deep .uni-forms-item {
  margin-bottom: 16rpx !important;
}

.checkbox__inner {
  border-radius: 50% !important;
}

.checklist-box {
  margin-right: 0 !important;
}

.u-tabs__wrapper__nav__item__text {
  font-size: 36rpx !important;
}
// ---------

.normal-login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  .toggle_tabs {
    width: 100%;
    height: 74%;
    background: #fff;
    position: absolute;
    bottom: 0;
    overflow: hidden;
    border-radius: 48rpx 48rpx 0rpx 0rpx;
  }

  .login_bg {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: -1;
  }
  .login_tab {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 650rpx !important;
    margin: 0 auto;

    // 记住密码
    .radio_group {
      margin-top: 40rpx;
      width: 100%;
      text-align: left;
      display: flex;
      align-items: center;
      justify-content: left;
    }

    .sub_btn {
      width: 654rpx;
      height: 88rpx;
      background: #269e93;
      border-radius: 100rpx 100rpx 100rpx 100rpx;
      margin: 0;
      margin-top: 30rpx;
      font-size: 36rpx;
    }
    .xieyi {
      margin-top: 30rpx;
      display: flex;
      font-size: 24rpx;
      align-items: center;
      color: #c3c3c3;
      .text_color {
        color: #9c9c9c;
      }
    }
  }

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 15%;

    image {
      border-radius: 4px;
    }

    .title {
      margin-left: 10px;
    }
  }

  .login-form-content {
    text-align: center;
    // margin: 20px auto;
    // margin-top: 15%;
    // width: 80%;
    .password {
      &::placeholder {
        font-size: 16rpx; /* 调整实心点的大小 */
      }
    }

    .input-item {
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 20px;

      .icon {
        font-size: 38rpx;
        margin-left: 10px;
        color: #999;
      }

      .input {
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        padding-left: 15px;
      }
    }

    .login-btn {
      margin-top: 40px;
      height: 45px;
    }

    .reg {
      margin-top: 15px;
    }

    .xieyi {
      color: #333;
      margin-top: 20px;
    }
  }
}

.login-code-img {
  position: absolute;
  z-index: 100;
  top: 50%;
  transform: translateY(-50%);
  right: 28rpx;
  width: 140rpx;
  height: 56rpx;
}
</style>
